/****************************************************
          File Name:35-3.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Tue 02 Sep 2014 06:54:29 PM CST
*****************************************************/
// RUN AS ROOT
// in 'top' command , can clearly see the parent and child share the CPU time
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
#include<signal.h>
#include<sched.h>
#include<sys/times.h>

int run(void)
{
    struct tms buf;
    long ti=0;
    float len;
    float es=4;
    float oes=1;
    
    ti=sysconf(_SC_CLK_TCK);

    for(;;)
    {
        times(&buf);
        len=buf.tms_utime/(double)ti;

        if(0.25==(float)(len/es))
        {
            es+=4;
            printf("%d eats %.3f CPU time\n",getpid(),len);
        } 
        if((len/oes)==1.0)
        {
            oes+=1;
            sched_yield();
        }
        if(len==3)
            break;
    }       
    return 0;
}

int main()
{
    struct sched_param pa;
    pa.sched_priority=10;
    sched_setscheduler(getpid(),SCHED_FIFO,&pa);
    if(errno)
    {
        perror("set");
        exit(1);
    }

    switch(fork())
    {
        case -1: exit(1);
        case 0:
             run();
             break;
        default:
             run();
             break;
    }
    exit(0); // will never run
}
